<?php

// +----------------------------------------------------------------------
// |采购服务层
// +----------------------------------------------------------------------

namespace app\admin\system;

use think\facade\Cache;
use think\facade\Db;
use app\admin\Model\SupplierModel;
use app\common\Model\UserModel;
use app\admin\Model\PurchaseModel;
use app\common\Model\StroageModel;
use think\facade\Request;
/**
 * 采购管理
 */
class PurchaseService
{    
 
      /**
    * 采购列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  index($param){
      
        $params=$param['params'];
        $where=[];
        //查询业务员
        if( $params['user_id']){
            $purchaseid=Db::name('purchare_items')->where(['user_id' => $params['user_id'], ['purchase_id', '<>', '']])->column('purchase_id'); 
            $where[] = ['id','in',$purchaseid];           
        }
       
        //查询localsku
        if( $params['localsku']){
            $purchase_id=Db::name('purchare_items')->where([['localsku','like','%'.$params['localsku'].'%'],['purchase_id','<>','']])->column('purchase_id');      
            if(isset($purchaseid)){
                $purchase_id=array_intersect($purchase_id,$purchaseid);
            }  
         $where[] = ['id','in',$purchase_id];        
        }
        //查询仓库
        if($params['storage_id']){
            $where[] =['storage_id','=',$params['storage_id']];
        }
        //查询采购单状态
        if($params['status']){
            $where[] =['paid_status','=',$params['status']];
        }
        //查询支付状态           
        if($params['paid_status'] || $params['paid_status']==0){   
            $where[] = ['paid_status','=',$params['paid_status']];
        }  
        //查询采购单       
        if($params['purchase_no']){
              $pno = explode("\n", $params['purchase_no']);   
              array_pop($pno);         
            foreach ($pno as $k => $v){              
                $pno[$k] = trim($v);
             }         
            $where[] = ['purchase_no','in',$pno];
        }       
         //查询1688单号     
        if($params['ordernum']){
              $ordernum = explode("\n", $params['ordernum']);   
              array_pop($ordernum);         
            foreach ($ordernum as $k => $v){              
                $ordernum[$k] = trim($v);
             }         
            $where[] = ['order_num','in',$ordernum];
        }
        if(isset($params['timeSearch']) && isset($params['dateRanges'])){
            //付款时间
              if(isset($params['dateRanges']['paid_time'])){
             		$createtime_paidstart = $params['dateRanges']['paid_time'][0];
                    $createtime_paidend = $params['dateRanges']['paid_time'][1]." 23:59:59";
                    $where[]=['paid_time','between',[$createtime_paidstart,$createtime_paidend]];
              }
              //下单时间
              if(isset($params['dateRanges']['createtime'])){
             		$createtime_createstart = $params['dateRanges']['createtime'][0];
                    $createtime_createend = $params['dateRanges']['createtime'][1]." 23:59:59";
                    $where[]=['createtime','between',[$createtime_createstart,$createtime_createend]];
              }
              //完结时间时间
              if(isset($params['dateRanges']['finish_time'])){
             		$createtime_finishtart = $params['dateRanges']['finish_time'][0];
                    $createtime_finishend = $params['dateRanges']['finish_time'][1]." 23:59:59";
                    $where[]=['finish_time','between',[$createtime_finishtart,$createtime_finishend]];
              }

        }
       
        
        // $where[] = ['status','=',1];  
        $list=Db::name('purchare')->where($where)->order('id desc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();
      
         if($list['data']){
            $supplierfo= (new SupplierModel())->getActivelist();  //获取供应商
            $getpaid_status= (new PurchaseModel())->getpaid_status();   //获取支付状态
            $getstatus= (new PurchaseModel())->getstatus();   //采购单状态
            $getStroagestatus= (new StroageModel())->getActivelist();   //收货仓库
            foreach ($list['data'] as $key => $value) { 
                $list['data'][$key]['paid_status_name'] = isset($value['paid_status'])?$getpaid_status[$value['paid_status']]:'';
                $list['data'][$key]['status_name'] =isset($value['status'])? $getstatus[$value['status']]:'';
                $list['data'][$key]['stroage_name'] = isset($value['storage_id'])?$getStroagestatus[$value['storage_id']]['name']:'';
                $list['data'][$key]['company_name'] = isset($value['s_id'])?$supplierfo[$value['s_id']]['name']:'';
            } 
         }
         
       //查询各种统计
       // 初始化统计数组
        $count = [
            'valid_count' => 0,
            'singular_count' => 0,
            'unpaid_total' => 0,
            'paid_total' => 0,
            'total_freight' => 0,
            'count' => [0, 0, 0, 0, 0] // 对应状态0-4的计数
        ];    
        $list_count=Db::name('purchare')->where($where)->order('id desc')->select()->toArray();
        if( $list_count){
         
            // 定义状态映射关系
            $statusIndexMap = [
                '0' => 0, // 取消采购单
                '1' => 1, // 采购中
                '2' => 2,   // 采购中的数据
                '3' => 3,   // 入库的采购单
                '4' => 4    // 完成的采购单
            ];

            foreach ($list_count as $v) {
                // 有效的件数统计（单数跟件数）
                if ($v['status'] != 0) {
                    $count['valid_count'] += $v['quantity'];
                    $count['singular_count'] += 1;
                    
                    // 付款状态统计
                    $count[($v['paid_status'] == 0 ? 'unpaid_total' : 'paid_total')] += $v['amount'];
                    
                    // 运费统计
                    $count['total_freight'] += $v['shipprice'];
                }
                
                // 状态计数统计
                if (isset($statusIndexMap[$v['status']])) {
                    $count['count'][$statusIndexMap[$v['status']]] += 1;
                }
            }
         }

        $data['count_quantity'] = $count;
        $data['list']=$list['data'];
        $data['total']=$list['total'];  
        return $data; 
    }

      /**
    * 取消采购单
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  cancel_purchase($param){
       $params=$param['params'];
       $id=$params['id'];
       $model=new PurchaseModel();
       $purchaseinfo=$model->where('id',$id)->find();
       if($purchaseinfo['status']==0){
          error('该采购单已取消');
       }
       $user_id=getuser()['id'];      
        Db::startTrans();
        try{        
            $model->where('id',$id)->update(['status'=>0]);
            DB::name('purchare_items')->where('purchase_id','=',$id )->where('status',1 )->update(['status'=>3,'operator'=>$user_id,'cancel_time'=>date('Y-m-d H:i:s')]);
            Db::commit();
            return true;
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 记录错误或返回错误信息
            error('处理失败'.$e->getMessage());
        }       
       return true;  

    }


      /**
    * 采购列表详情
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  purchase_detail($param){
         $params=$param['params'];    
         $id=$params['id']; 
         $model=new PurchaseModel();
         $supplierfo= (new SupplierModel())->getActivelist();  //获取供应商
         $buyerinfo= (new UserModel())->getuserlist(3);  //获取采购员
         $getstatus= (new PurchaseModel())->getstatus();   //采购单状态
         $getStroagestatus= (new StroageModel())->getActivelist();   //收货仓库 
         $userinfo= (new UserModel())->getActivelist();  //获取业务

         $data=$model->where(['id'=>['=',$id]])->find()->toArray(); 
         $data['buyer_name']=isset($data['buyer_id'])?$buyerinfo[$data['buyer_id']]['nickname']:'';
         $data['stroage_name'] = isset($data['storage_id'])?$getStroagestatus[$data['storage_id']]['name']:'';
         $data['company_name'] = isset($data['s_id'])?$supplierfo[$data['s_id']]['name']:'';
         $data['status_name'] = isset($data['status'])?$getstatus[$data['status']]:'';
          //查询入库单的
        $where['purchase_id']=['=',$id];
        $where['status']=['=',2];
        $res= DB::name('purchare_items')->where($where )->field('product_id,localsku,s_id,buyer_id,count,storage_id,id,actualPrice,img,user_id,product_link')->select()->toArray();
        //查询入库数据
        $instorage_item= DB::name('instorage_item')->where('purchase_id','=',$id)->group('purchase_id,product_id')->column('sum(product_count),product_id','product_id');
        if($res){
            foreach ($res as $key => $value) { 
                //算出缺货数据 = 采购数量-入库数据
                $inventory_quantity=isset($instorage_item[$value['product_id']])?$instorage_item[$value['product_id']]:0;
                $stock= $value['count']- $inventory_quantity;
                $res[$key]['stroage_name'] = isset($value['storage_id'])?$getStroagestatus[$value['storage_id']]['name']:'';
                $res[$key]['company_name'] = isset($value['s_id'])?$supplierfo[$value['s_id']]['name']:'';   
                $res[$key]['stock'] = $stock;   //缺货数据
                $res[$key]['inventory_quantity'] = $inventory_quantity;   //入库数据
                $res[$key]['nickname']=isset($value['user_id'])?$userinfo[$value['user_id']]['nickname']:'';               
                
            }
        }
        $list['list']=$data;
        $list['detail_list']=$res;
        return $list; 
    }
    
      /**
    * 待采购列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  getList($param){
      
        $params=$param['params'];
        $where[] = ['status','=',1];       
        if($params['s_id']){
            $where[] = ['s_id', '=', $params['s_id']];
        }   
    //      // 查询前 临时禁用 ONLY_FULL_GROUP_BY（开发环境可用）
    //     Db::execute("SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");
    //     $field =  'count(1) as count,s_id,buyer_id,id';          
    //     $purchase_items_list = Db::name('purchare_items')->field($field)->where($where)->group('s_id')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();  
    //     // 查询后恢复
    //    Db::execute("SET SESSION sql_mode=(SELECT CONCAT(@@sql_mode,',ONLY_FULL_GROUP_BY'))");

       //闭包查询
       $query = function($where, $field, $params){
            $query =Db::name('purchare_items')               
                ->field($field)
                ->order("id asc")
                ->where($where);
             return $query->group("s_id")->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();            
        };
        // 列表查村字段
        $field ='count(1) as count,s_id,buyer_id,id';       
        $purchase_items_list = $query($where,$field,$params);

        if($purchase_items_list['data']){
            $supplierfo= (new SupplierModel())->getActivelist();  //获取供应商
            $buyerinfo= (new UserModel())->getuserlist(3);  //获取采购用户
            foreach ($purchase_items_list['data'] as $key => $value) { 
                   $purchase_items_list['data'][$key]['supplier_name']=$supplierfo[$value['s_id']]['name'];;
                   $purchase_items_list['data'][$key]['buyer_name']=$buyerinfo[$value['buyer_id']]['nickname'];;
                //    $authgroups_list['data'][$key]['zipcode']=$sender['zipcode'];               
            }
       }
        $data['list']=$purchase_items_list['data'];
        $data['total']=$purchase_items_list['total'];  
        return $data; 
    }

      /**
    * 采购待采购列表生成采购
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  create_purchase($param){
        $model=new PurchaseModel();
        $params=$param['params'];
        $type=$params['type'];//类型  1=是选择供应商过来数据  2 是选择localsku 过来的
        $selectids=$params['selectids'];//选择的id
        if($type==1){             
            //1=是选择供应商过来数据
            // 查询前 临时禁用 ONLY_FULL_GROUP_BY（开发环境可用）
            Db::execute("SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");
            $preItems=Db::name('purchare_items')->whereIn('s_id',explode(',',$selectids) )->group('s_id,buyer_id,storage_id')->field('s_id,buyer_id,storage_id,sum(totalPrice) as totalPrice,sum(count) as purchasenum,group_concat(id) as preid')->select()->toArray();
            // 查询后恢复
            Db::execute("SET SESSION sql_mode=(SELECT CONCAT(@@sql_mode,',ONLY_FULL_GROUP_BY'))");
        }else{
            $preItems=Db::name('purchare_items')->whereIn('id',explode(',',$selectids) )->group('s_id,buyer_id,storage_id')->field('s_id,buyer_id,storage_id,sum(totalPrice) as totalPrice,sum(count) as purchasenum,group_concat(id) as preid')->select()->toArray();
        }
     
        if($preItems){
            Db::startTrans();
            try{
                foreach( $preItems as $v){
                    $data['amount'] = $v['totalPrice'];
                    $data['storage_id'] = $v['storage_id'];
                    $data['quantity'] = $v['purchasenum'];
                    $data['amount'] = $v['totalPrice'];
                    $data['s_id'] = $v['s_id'];
                    $data['buyer_id'] = $v['buyer_id'];
                    $data['quantity'] = $v['purchasenum'];
                    $data['createtime'] = date('Y-m-d H:i:s');
                    $data['createymd'] = date('Ymd');
                    $purchareId = Db::name('purchare')->insertGetId($data);
                    $preid=$v['preid'];
                    //生成采购单的订单号
                    if ($purchareId < 10 && $purchareId > 0){
                        $purchase_no = date('Ymd', time()) . '0' . $purchareId;
                    }
                    elseif ($purchareId >= 10){
                        $purchase_no = date('Ymd', time()) . $purchareId;
                    }

                    //更新purchase表 采购单号，prepurchase 采购单id/采购单号
                    Db::execute("update erp_purchare set purchase_no='$purchase_no' where id='$purchareId'");
                    Db::execute("update erp_purchare_items set purchase_id='$purchareId',purchase_no='$purchase_no',status='2' where id in ($preid)");

                }
                Db::commit();
                return true;
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                // 记录错误或返回错误信息
               error('处理失败'.$e->getMessage());
            }        
        }
    }

    /**
    * 取消待采购单详情单
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  cancel_purchase_itmes($param){     
        $user_id=getuser()['id'];           
        $params=$param['params'];
        $type=$params['type'];//类型  1=是选择供应商过来数据  2 是选择localsku 过来的
        $selectids=$params['selectids'];//选择的id
       
        if($type==1){             
            //1=是选择供应商过来数据
             $relutes= DB::name('purchare_items')->whereIn('s_id',explode(',',$selectids) )->where('status',1 )->update(['status'=>3,'operator'=>$user_id,'cancel_time'=>date('Y-m-d H:i:s')]);
        }else{
            $relutes= DB::name('purchare_items')->whereIn('id',explode(',',$selectids) )->where('status',1 )->update(['status'=>3,'operator'=>$user_id,'cancel_time'=>date('Y-m-d H:i:s')]);
        }
        if($relutes){
            return true;
        }else{
            error('取消');
        }        
    }
    /**
    * 待采购单详情单
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  procurement_itmes($param){
        $params=$param['params'];    
        $where[] = ['status','=',1];       
        $where[] = ['s_id','=',$params['id']];                
        if($params['localsku']){
            $where[] = ['localsku', 'like', '%'. $params['localsku']. '%'];
        } 
        if($params['buyer_id']){
            $where[] = ['buyer_id', '=', $params['buyer_id']];
        }   
        $buyerinfo= (new UserModel())->getuserlist(3);  //获取采购员  
        $stroageinfo= (new StroageModel())->getActivelist();  //获取仓库
        $supplierfo= (new SupplierModel())->getActivelist();  //获取供应商
        $relutes= DB::name('purchare_items')->where($where )->field('localsku,s_id,buyer_id,count,storage_id,id,actualPrice,totalPrice')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();
        if($relutes['data']){
             foreach ($relutes['data'] as $key => $value) { 
                   $relutes['data'][$key]['supplier_name']=$supplierfo[$value['s_id']]['name'];
                   $relutes['data'][$key]['buyer_name']=$buyerinfo[$value['buyer_id']]['nickname'];
                   $relutes['data'][$key]['storage_name']=$stroageinfo[$value['storage_id']]['name'];                      
             }
        }       

        $data['list']=$relutes['data'];
        $data['total']=$relutes['total'];  
        return $data; 
    }

     /**
    * 修改待采购详情单采购数量列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function purchase_save_num($param){
        $params=$param['params'];    
        $type=$params['type'];//类型  1=是待采购这里更新采购数据量  2=是修改采购单1688单号，填写运费的单号  3=是，更新采购单价格 
        $id=$params['id'];
        if($type==1){
            //修改待采购这里更新采购数据量  
            $count=$params['count'];
            $actualPrice=$params['actualPrice'];
            $relutes= DB::name('purchare_items')->whereIn('id',$id )->where('status',1 )->update(['count'=>$count,'totalPrice'=>$count* $actualPrice]);
        }elseif($type==2){
            //修改采购单1688单号，填写运费的单号  
            $notes      =  $params['notes'];
            $order_num  =  $params['order_num'];
            $shipprice  =  $params['shipprice'];
            if($notes){
                $data['notes'] = $notes;
            }
            if($order_num){
                $data['order_num'] = $order_num;
            }
            if($shipprice){
                $data['shipprice'] = $shipprice;
            }
              $relutes= DB::name('purchare')->whereIn('id',$id )->update($data);
        }
        
        if($relutes){
            return true;
        }else{
            error('修改失败');
        }
    }

        /**
    * 添加采购单的
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function addpurchase($param){
       
        $baseinfo=$param['baseinfo'];
        $datalist=$param['datalist'];
        $dataArr=[];
        if($datalist){
            foreach ($datalist as $key => $value) {                
                $data['product_link'] = $value['product_link'];
                $data['product_id'] = $value['id'];
                $data['code'] = $value['code'];
                $data['parent_product_id'] = $value['pid'];
                $data['localsku'] = $value['localsku'];
                $data['s_id'] = $value['s_id'];
                $data['buyer_id'] = $baseinfo['buyer_id'];
                $data['count'] = $value['num'];
                $data['storage_id'] = $baseinfo['storage'];
                $data['actualPrice'] = $value['price'];
                $data['totalPrice'] = $value['price']*$value['num'];
                $data['img'] = $value['img'];
                $data['user_id'] = $baseinfo['user_id'];
                $data['createtime'] = date('Y-m-d H:i:s');
                $data['createymd'] = date('Ymd');   
                $dataArr[]=$data;    
            }     
        }
        $relute = Db::name('purchare_items')->insertAll($dataArr);
        if($relute){
            return true;
        }else{
            error('添加失败');
        }         
    }

   /**
    * 添加采购单的
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function import_purchase($param){
        //上传文件
        if(Request::file("file")){           
             $exlcel=ImportExcel(Request::file("file"));
            return $exlcel;
       }else{
          $params=$param['params'];           
          if($params['data']){
             $user_id=getuser()['id'];
              unset($params['data'][0]);
              $localsku=$nickname=$storage= [];            
              foreach ($params['data'] as $key => $value) {
                      $localsku[]=trim($value[0]);    
                      $nickname[]=trim($value[2]);  
                      $storage[]=trim($value[3]);  
                      if($value[1]=='' || $value[1]==0){
                          error('导入的采购数据不能为空或者为0');die;
                      }
                    if(empty($value[0])){
                        error('导入的采购数据不能为空');die;
                    }
              }          
               
                $storage_name=Db::name('storage')->whereIn('name',$storage)->where('status',1)->column('name,id','name');  
                $buyerinfo=Db::name('users')->alias('a')->join('auth_group_access aga','a.id = aga.uid')->whereIn('nickname',$nickname)->wherein('aga.group_id',4)->column('id,nickname','nickname');
                $productdata=Db::name('products')->whereIn('localsku',$localsku)->where('pid','<>',0)->where('status',1)->column('localsku,img,id,pid,code,price,s_id,product_link','localsku');           
                foreach ($params['data'] as $key => $value) {
                        $data['product_link'] = $productdata[$value[0]]['product_link'];
                        $data['product_id'] = $productdata[$value[0]]['id'];
                        $data['code'] = $productdata[$value[0]]['code'];
                        $data['parent_product_id'] =$productdata[$value[0]]['pid'];
                        $data['localsku'] = $value[0];
                        $data['s_id'] = $productdata[$value[0]]['s_id'];
                        $data['buyer_id'] = $user_id ;
                        $data['count'] = $value[1];
                        $data['storage_id'] =$storage_name[$value[3]]['id'];
                        $data['actualPrice'] = $productdata[$value[0]]['price'];
                        $data['totalPrice'] = $productdata[$value[0]]['price']*$value[1];
                        $data['img'] = $productdata[$value[0]]['img'];
                        $data['user_id'] = $buyerinfo[$value[2]]['id'];
                        $data['createtime'] = date('Y-m-d H:i:s');
                        $data['createymd'] = date('Ymd');   
                        $dataArr[]=$data;    
                }
                $relute = Db::name('purchare_items')->insertAll($dataArr);
                if($relute){
                    return true;
                }else{
                    error('添加失败');
                }    
            }
           
       }
    }
    



}